<template>
  <div class="login-box">
    <div class="login-background base-flex">
      <div class="login-content">
        <div class="login-role"></div>
        <div class="login-main">
          <i>EAP管理系统</i>
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="单点登录" name="first">

              <el-form label-position="top" :model="ruleForm" status-icon :rules="rules" ref="ruleF" label-width="100px"
                class="login-form">
                <el-form-item>
                  <el-button type="primary" @click="SSOLogin('ruleF')">统一登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="维护登录" name="second">
              <el-form label-position="top" :model="ruleForm" status-icon :rules="rules" ref="ruleF" label-width="100px"
                class="login-form">
                <el-form-item label="用户名" prop="username">
                  <el-input prefix-icon="el-icon-user" v-model="ruleForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input prefix-icon="el-icon-lock" type="password" v-model="ruleForm.password" autocomplete="off"
                    show-password></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="totpForm('ruleF')">登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>


          <!-- <el-form label-position="top" :model="ruleForm" status-icon :rules="rules" ref="ruleF" label-width="100px"
            class="login-form">
            <el-form-item label="用户名" prop="username"  v-show="false" >
              <el-input prefix-icon="el-icon-user" type="password" v-model="ruleForm.username"
                autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" v-show="false">
              <el-input prefix-icon="el-icon-lock" type="password" v-model="ruleForm.password"
                autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="SSOLogin('ruleF')">统一登录</el-button>
            </el-form-item>
          </el-form> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as crypto from "crypto-browserify";
import axios from "axios";
import jsCookie from 'js-cookie'
import { Loading } from 'element-ui';
//import Oidc from 'oidc-client';
// let currentHost="http://localhost:8081";
//       const settings={
//         authority: "https://account-api.dev.lead.cn:9444",//认证中心地址
//         client_id: '9ae0d2e9caed4f36953adcaae469ebf8',//客户端id
//         client_secret:"b4411478f2ba40e3bccaa2611a29d2cb",
//         redirect_uri: currentHost + '/#/ssocallback#',//统一登陆成功后跳转地址
//         post_logout_redirect_uri: currentHost + '/#/ssologinout#',//统一登出成功后跳转地址 一般在此页面清空浏览器token
//         response_type: `id_token token`,
//         scope: 'openid profile',
//       };
// const mgr = new Oidc.UserManager(settings);
export default {
  name: 'loginView',
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            Pattern: '[a-zA-Z0-9_]*',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            Pattern: '[a-zA-Z0-9_]*',
            trigger: 'blur',
          },
          { min: 6, message: '请输入至少6个字符', trigger: 'blur' },
        ],
      },
      activeName: 'first',
    };
  },
  methods: {
    async submitForm1(formName) {
      //console.log(this.ruleForm.password)
      console.log(formName);
      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      //this.$store
      //  .dispatch('permission/login', { username: 'admin' })
      //  .then(() => {
      //   this.$router.push({ path: '/home' });
      // });
      //   } else {
      //     console.log("error submit!!");
      //     return false;
      //   }
      // });
      // 生成ECDH密钥对
      const ecdh = crypto.createECDH("prime256v1");
      this.publicKey = ecdh.generateKeys("base64");
      console.log('qt_publicKey:' + this.publicKey);
      const pb_response = await axios.post("/webapi/ecdh/GetPublicKey");
      this.ht_publicKey = pb_response.data.PublicKey;
      console.log('ht_publicKey:' + this.ht_publicKey);
      // 发送公钥到后端
      const dhresponse = await axios.post("/webapi/ecdh/dh", { PublicKey: this.publicKey });


      // 接收共享密钥
      //const response = await axios.post("/webapi/ecdh/GetPublicKey");
      this.sharedKey = dhresponse.data.SharedKey;
      console.log('sharedKey:' + this.sharedKey);
      let IV = crypto.randomBytes(16);
      let IVBase64 = IV.toString("base64");
      console.log('IV:' + IVBase64);
      let key = Buffer.from(this.sharedKey, "base64");
      console.log('转化IV');
      // 加密密码
      const cipher = crypto.createCipheriv(
        "aes-256-cbc",
        key,
        IV
      );
      console.log('原始密码:' + this.ruleForm.password);
      let passwordbyte = Buffer.from(this.ruleForm.password);
      console.log('初始化AES');

      const encryptedPassword = Buffer.concat([
        cipher.update(passwordbyte),
        cipher.final(),
      ]);
      console.log('AES加密');
      let password_enc = encryptedPassword.toString("base64");
      console.log('加密后的password' + password_enc);
      // 发送加密后的用户名和密码到后端
      const loginresponse = await axios.post("/webapi/ecdh/login", {
        username: this.ruleForm.username,
        password: password_enc,
        SharedKey: this.sharedKey,
        IV: IVBase64
      });
      console.log(loginresponse);
      this.$router.push({ path: '/home' });
    },
    async totpForm(formName) {
      //console.log(this.ruleForm.password)
      console.log(formName);
      let loadingInstance = Loading.service({ fullscreen: true });
      // 发送加密后的用户名和密码到后端
      const loginresponse = await axios.post("/webapi/ecdh/totplogin", {
        username: this.ruleForm.username,
        password: this.ruleForm.password,
        SharedKey: "",
        IV: ""
      });
      console.log(loginresponse);
      if (loginresponse.data.Token != "" & loginresponse.data.Token != null) {
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + loginresponse.data.Token;
        localStorage.setItem('Authorization', loginresponse.data.Token);
        localStorage.setItem('AuthMode', "Local");
        jsCookie.set('Authorization', loginresponse.data.Token)
        loadingInstance.close();
        this.$message({
          message: '恭喜你，登录成功',
          type: 'success'
        });
        //登录成功
        this.$router.push({ path: '/home' });
      }
      else {
        this.$message.error("登录失败");
        this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          loadingInstance.close();
        });
      }
    },
    async submitForm(formName) { this.$router.push({ path: '/home' }); },
    SSOLogin(formName) {
      if (this.$store.state.systemconfig.userManager) {
        this.$store.state.systemconfig.userManager.signinRedirect()
      } else {
        console.error('UserManager not found')
      }
    },
    async SSO_GetToken() {
      // await mgr.getAcessToken().then(
      //   acessToken => {
      //     console.log("SSO_GetToken");
      //     console.log("Token"+acessToken);
      //     axios.defaults.headers.common['Authorization'] = 'Bearer ' + acessToken
      //   }, err => {
      //     console.log(err)
      //   });  
    },
    async SSO_GetUser() {
      let cache_router = this.$router;
      let cache_nextTick = this.$nextTick;
      let cache_message = this.$message;
      let loadingInstance = Loading.service({ fullscreen: true });
      await this.$store.state.systemconfig.userManager.getUser().then(async function (user) {
        console.log("SSO_GetUser");
        console.log(user);
        if (user == null) {
          loadingInstance.close();
          console.log("未登录");
          return;
        }

        let ssouser = {};
        ssouser.auth_time = user.profile.auth_time;
        ssouser.expires_at = user.expires_at;
        ssouser.email = user.profile.email;
        ssouser.idp = user.profile.idp;
        ssouser.name = user.profile.name;
        ssouser.role = user.profile.role;
        ssouser.sid = user.profile.sid;
        ssouser.sub = user.profile.sub;
        ssouser.user_id = user.profile.user_id;
        console.log(ssouser);

        //sso登录接口
        // 生成ECDH密钥对
        const ecdh = crypto.createECDH("prime256v1");
        let publicKey = ecdh.generateKeys("base64");
        console.log('qt_publicKey:' + publicKey);
        const pb_response = await axios.post("/webapi/ecdh/GetPublicKey");
        let ht_publicKey = pb_response.data.PublicKey;
        console.log('ht_publicKey:' + ht_publicKey);
        // 发送公钥到后端
        const dhresponse = await axios.post("/webapi/ecdh/dh", { PublicKey: publicKey });


        // 接收共享密钥
        //const response = await axios.post("/webapi/ecdh/GetPublicKey");
        let sharedKey = dhresponse.data.SharedKey;
        console.log('sharedKey:' + sharedKey);
        let IV = crypto.randomBytes(16);
        let IVBase64 = IV.toString("base64");
        console.log('IV:' + IVBase64);
        let key = Buffer.from(sharedKey, "base64");
        console.log('转化IV');
        // 加密密码
        const cipher = crypto.createCipheriv(
          "aes-256-cbc",
          key,
          IV
        );
        let passwordbody = JSON.stringify(ssouser);
        console.log('原始载荷:' + passwordbody);
        let passwordbyte = Buffer.from(passwordbody);
        console.log('初始化AES');

        const encryptedPassword = Buffer.concat([
          cipher.update(passwordbyte),
          cipher.final(),
        ]);
        console.log('AES加密');
        let password_enc = encryptedPassword.toString("base64");
        console.log('加密后的password' + password_enc);
        // 发送加密后的用户名和密码到后端
        const loginresponse = await axios.post("/webapi/ecdh/ssologin", {
          username: ssouser.name,
          password: password_enc,
          SharedKey: sharedKey,
          IV: IVBase64
        });
        console.log(loginresponse);
        console.log("Token:" + loginresponse.data.Token)
        if (loginresponse.data.Token != "" & loginresponse.data.Token != null) {
          axios.defaults.headers.common['Authorization'] = 'Bearer ' + loginresponse.data.Token;
          localStorage.setItem('Authorization', loginresponse.data.Token);
          localStorage.setItem('AuthMode', "SSO");
          jsCookie.set('Authorization', loginresponse.data.Token)
          cache_nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            loadingInstance.close();
          });
          cache_message({
            message: '恭喜你，登录成功',
            type: 'success'
          });
          //登录成功
          cache_router.push({ path: '/home' });
        }
        else {
          cache_message.error("登录失败");
          cache_nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
            loadingInstance.close();
          });
        }


      });
    },
    async SSO_Loginout() {
      console.log("SSO_Loginout");
      this.$store.state.systemconfig.userManager.signoutRedirect();
    }
  },
  created() {
    console.log('login.vue created')
  },
  mounted: function () {
    this.$nextTick(function () {
      console.log('login.vue updated')
      this.SSO_GetToken();
      this.SSO_GetUser();
    })
  },
};
</script>
